package com.example.loginproject.view.views

import android.animation.ValueAnimator
import android.annotation.SuppressLint
import android.content.AttributionSource
import android.content.Context
import android.graphics.Canvas
import android.graphics.Color
import android.graphics.Paint
import android.graphics.Rect
import android.graphics.Typeface
import android.graphics.fonts.Font
import android.os.Build
import android.text.TextPaint
import android.util.AttributeSet
import android.util.TypedValue
import android.view.View
import android.view.animation.AccelerateDecelerateInterpolator
import androidx.annotation.RequiresApi
import com.example.loginproject.R
import com.example.loginproject.tool.MyLog
import java.time.temporal.ValueRange
import java.util.Timer
import java.util.TimerTask

//需要显示的文本内容，文本的字体大小，
class CustomTextView:View {
    private  var rateText:String = "0%"
    private lateinit var mText:String
    private  var mTextSize:Float = 14F
    private lateinit var mTextFont:Font
    var clickListener:(()->Unit)? = null
    private val mRatePaint :TextPaint by lazy {
        TextPaint().apply {
            color = Color.YELLOW
            textSize = sp2px(15f)
        }
    }
    private var mSweepAngle = 0f
    private val mPaint:TextPaint by lazy {
        TextPaint().apply {
            color = Color.GREEN
            textSize = mTextSize
            typeface = Typeface.DEFAULT//系统字体
        }
    }
    private val mCirclePaint: Paint by lazy {
        Paint().apply {
            color = Color.BLUE
            strokeWidth =dp2px(20)//画笔粗细
            isAntiAlias = true //抗锯齿
            style = Paint.Style.STROKE//stroke描边 fill填满，strokeandfill 描边加填满
        }
    }
    private val mArcPaint:Paint by lazy{
        Paint().apply {
            color = Color.WHITE
            strokeWidth = dp2px(20)
            strokeCap = Paint.Cap.ROUND//设置两端样式ROUND圆角BUTT横切
            //strokeJoin = Paint.Join.ROUND
            isAntiAlias = true
            style = Paint.Style.STROKE
        }
    }
    @RequiresApi(Build.VERSION_CODES.Q)
    constructor(context: Context):super(context){init(context,null)}
    @RequiresApi(Build.VERSION_CODES.Q)
    constructor(context: Context, attrs:AttributeSet?):super(context,attrs){init(context, attrs)}
    @SuppressLint("SuspiciousIndentation", "Recycle")
    @RequiresApi(Build.VERSION_CODES.Q)
    private fun init(context: Context, attrs: AttributeSet?){
        //解析自定义属性
        context.obtainStyledAttributes(attrs, R.styleable.CustomTextView).apply {
           mText = getString(R.styleable.CustomTextView_text)?:""
            mTextSize = getDimension(R.styleable.CustomTextView_fontSize,14f)
           val fontType = getInteger(R.styleable.CustomTextView_textFont,1)
            recycle()
            if(fontType == 2){
                mTextFont = Font.Builder(context.resources,R.font.zitiaozichang).build()
            }
            setOnClickListener {
                clickListener?.let{it()}
//                val timer = Timer()
//                timer.schedule(object :TimerTask(){
//                    override fun run() {
//                        mSweepAngle +=18
//                        invalidate()//重新绘制
//                        if(mSweepAngle == 360f){
//                            timer.cancel()
//                        }
//                    }
//                },0,100)
                val angleAnimator = ValueAnimator.ofFloat(0f,360f)
                angleAnimator.duration = 2000
                //设置有无终点，INFINTE代表无限制的转动
                angleAnimator.repeatCount = ValueAnimator.INFINITE
                //转的方向
                angleAnimator.repeatCount = ValueAnimator.REVERSE
                //加速
                angleAnimator.interpolator = AccelerateDecelerateInterpolator()
                //启动
                angleAnimator.start()
                //监听value的变化
                angleAnimator.addUpdateListener {
                    //获取当前值
                    mSweepAngle = it.animatedValue as Float

                    val progress = (mSweepAngle/360*100).toInt()
                    rateText = "$progress%"
                  //重绘
                  invalidate()
                }
            }

        }
    }
    //onDraw和onMeasure会被多次调用，创建对象和耗时计算不能放在这两个下
    override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec)
        //定义变量并保存最终宽和高
        var mWidth = 0
        var mHeight = 0
        //获取外部设置的模式
        val widthMode = MeasureSpec.getMode(widthMeasureSpec)
        val widthSize = MeasureSpec.getSize(widthMeasureSpec)
        val heightMode = MeasureSpec.getMode(heightMeasureSpec)
        val heightSize = MeasureSpec.getSize(heightMeasureSpec)
        when (widthMode) {
            MeasureSpec.EXACTLY -> mWidth = widthSize
            MeasureSpec.AT_MOST -> mWidth = textWidth()
        }
        when (heightMode) {
            MeasureSpec.EXACTLY -> mHeight = heightSize
            MeasureSpec.AT_MOST -> mHeight = textHeight()
        }
        //告诉外部（父容器）自己的尺寸
        setMeasuredDimension(mWidth, mHeight)
    }

    override fun onDraw(canvas: Canvas) {
        drawText(canvas)
       drawCircle(canvas)
        drawArc(canvas)
        drawProgressText(canvas)

       }
    //绘制下载进度文本
    fun drawProgressText(canvas:Canvas?){
        val fontMetrics = mPaint.fontMetrics
        val sx = (width-mRatePaint.measureText(rateText))/2
        val sy = (height - fontMetrics.top-fontMetrics.bottom)/2
        canvas?.drawText(rateText,sx,sy,mRatePaint)
    }
    fun drawText(canvas:Canvas?){
        //基准线的距离：(descent+ascent)/2-descent
        //基线的Y的坐标=中心线的y坐标+基线到中心线的距离
        val metrics = mPaint.fontMetrics
        val sx = (width - mPaint.measureText(mText))/2
        val sy = (height-metrics.top-metrics.bottom)/2
        mPaint.color = Color.GRAY
        canvas?.drawText(mText,sx,sy,mPaint)
    }
    fun drawCircle(canvas: Canvas?){
        val cx = (width/2).toFloat()
        val cy = (height/2).toFloat()
        val radius = Math.min(width,height)/2 - dp2px(20)
        canvas?.drawCircle(cx,cy,radius,mCirclePaint)
    }
    fun drawArc(canvas: Canvas?){
        val cx = (width/2).toFloat()
        val cy = (height/2).toFloat()
        val radius = Math.min(width,height)/2 - dp2px(20)
        canvas?.drawArc(cx-radius,cy-radius,cx+radius,cy+radius,270f,mSweepAngle.toFloat(),false,mArcPaint)
    }


   private fun textWidth() = mPaint.measureText(mText).toInt()
   private fun textHeight():Int{
        val metrics = mPaint.fontMetrics
        return (metrics.bottom - metrics.top).toInt()
    }
    //px转化为dp//px是像素
     fun px2dp(px:Int):Int{
        return (px / context.resources.displayMetrics.density).toInt()
    }//dp转化成px
    fun dp2px(dp:Int) = context.resources.displayMetrics.density*dp
    //将sp转化成px
    fun sp2px(sp:Float):Float{
        return TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP,sp,context.resources.displayMetrics)
    }

}